import configparser
import json
import queue
import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton
from datetime import datetime
from CU.Command import FeedCommand
from CU.Feeding import FeedLine, FeedingConfig, Feeding, FeedStatus
from ui_untitled import  Ui_MainWindow
from COM.COM_Robot import RobotClient
from Expection import  Error_Code
from queue import Queue
from Model.RobotModel import *
import time
from queue import Queue
from Model.Position import Real_Position
from threading import Thread
from CU.Command import Status



class MainWindow(QMainWindow,Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.init_UI()
        self.init_Run()
        self.init_FeedLine()
        self.init_robot_info()
        start_Runing()

    def init_UI(self):
        self.horizontalSlider_J1.sliderReleased.connect(self.slider_valueChanged)
        self.horizontalSlider_J2.sliderReleased.connect(self.slider_valueChanged)
        self.horizontalSlider_J3.sliderReleased.connect(self.slider_valueChanged)
        self.horizontalSlider_J4.sliderReleased.connect(self.slider_valueChanged)
        self.horizontalSlider_J5.sliderReleased.connect(self.slider_valueChanged)
        self.horizontalSlider_J6.sliderReleased.connect(self.slider_valueChanged)
        self.pushButton_num1.clicked.connect(self.send_num_button_click)
        self.pushButton_num2.clicked.connect(self.send_num_button_click)
        self.pushButton_num3.clicked.connect(self.send_num_button_click)
        self.pushButton_num4.clicked.connect(self.send_num_button_click)
        self.pushButton_num5.clicked.connect(self.send_num_button_click)
        self.pushButton_num6.clicked.connect(self.send_num_button_click)
        self.pushButton_AddNum.clicked.connect(self.send_addNum_button_click)
        self.pushButton_SubNum.clicked.connect(self.send_subNum_button_click)
        self.pushButton_num_free.clicked.connect(self.send_num_button_click)
        self.lineEdit_num.returnPressed.connect(self.send_custom_num_returnPressed)
        int_validator = QIntValidator(0, 100, self)
        self.lineEdit_num.setValidator(int_validator)

        # self.horizontalSlider_J1.sliderReleased
        self.pushButton_startFeed.clicked.connect(self.send_startFeed_button_click)

    def init_Run(self):
        self.robotClient = None
        self.configReader = configparser.ConfigParser()

        self.command_position_quene = Queue()
        self.status_address = DataAddress()
        self.feedLine_dict = dir()
        self.command_quene = Queue()
        self.main_threading = None

        self.configReader.read('Seting.ini')
        ip = self.configReader.get('Robot_Feed', 'IPAddress')
        port = int(self.configReader.get('Robot_Feed', 'Port'))
        self.robotClient = RobotClient(ip, port, self.command_position_quene, self.status_address)
        try:
            self.robotClient.CreatConnect()
        except:
            return Error_Code.SYS_NETERROR

        if self.robotClient.is_Connect():
            return 0
        else:
            return Error_Code.NETERROR
        self.feeding = Feeding(self.robotClient) #临时

    def init_FeedLine(self):
        line_count = self.configReader.get('Robot_Feed', 'LineCount', fallback=0)
        self.configReader.read('Config/FeedLine.ini')
        for i in range(line_count):
            line_str = f'FeedLine{i+1}'
            safe_position = Real_Position()
            photo_position = Real_Position()
            feed_position = Real_Position()

            safe_position.X = self.configReader.get(line_str, 'SafePosition_x',  fallback=0)
            safe_position.Y = self.configReader.get(line_str, 'SafePosition_y', fallback=0)
            safe_position.Z = self.configReader.get(line_str, 'SafePosition_z', fallback=0)
            safe_position.U = self.configReader.get(line_str, 'SafePosition_u', fallback=0)
            safe_position.V = self.configReader.get(line_str, 'SafePosition_v', fallback=0)
            safe_position.W = self.configReader.get(line_str, 'SafePosition_w', fallback=0)

            photo_position.X = self.configReader.get(line_str, 'PhotoPosition_x', fallback=0)
            photo_position.Y = self.configReader.get(line_str, 'PhotoPosition_y', fallback=0)
            photo_position.Z = self.configReader.get(line_str, 'PhotoPosition_z', fallback=0)
            photo_position.U = self.configReader.get(line_str, 'PhotoPosition_u', fallback=0)
            photo_position.V = self.configReader.get(line_str, 'PhotoPosition_v', fallback=0)
            photo_position.W = self.configReader.get(line_str, 'PhotoPosition_w', fallback=0)


            feed_position.X = self.configReader.get(line_str, 'FeedPosition_x', fallback=0)
            feed_position.Y = self.configReader.get(line_str, 'FeedPosition_y', fallback=0)
            feed_position.Z = self.configReader.get(line_str, 'FeedPosition_z', fallback=0)
            feed_position.U = self.configReader.get(line_str, 'FeedPosition_u', fallback=0)
            feed_position.V = self.configReader.get(line_str, 'FeedPosition_v', fallback=0)
            feed_position.W = self.configReader.get(line_str, 'FeedPosition_w', fallback=0)

            self.feedLine_dict[str(i+1)] = FeedLine(safe_position, photo_position, feed_position)

        pass

    def init_robot_info(self):
        j1_min = int(self.configReader.get('Robot', 'j1_min'))
        j1_max = int(self.configReader.get('Robot', 'j1_max'))
        j2_min = int(self.configReader.get('Robot', 'j2_min'))
        j2_max = int(self.configReader.get('Robot', 'j2_max'))
        j3_min = int(self.configReader.get('Robot', 'j3_min'))
        j3_max = int(self.configReader.get('Robot', 'j3_max'))
        j4_min = int(self.configReader.get('Robot', 'j4_min'))
        j4_max = int(self.configReader.get('Robot', 'j4_max'))
        j5_min = int(self.configReader.get('Robot', 'j5_min'))
        j5_max = int(self.configReader.get('Robot', 'j5_max'))
        j6_min = int(self.configReader.get('Robot', 'j6_min'))
        j6_max = int(self.configReader.get('Robot', 'j6_max'))
        self.horizontalSlider_J1.setMinimum(j1_min)
        self.horizontalSlider_J1.setMaximum(j1_max)
        self.horizontalSlider_J2.setMinimum(j2_min)
        self.horizontalSlider_J2.setMaximum(j2_max)
        self.horizontalSlider_J3.setMinimum(j3_min)
        self.horizontalSlider_J3.setMaximum(j3_max)
        self.horizontalSlider_J4.setMinimum(j4_min)
        self.horizontalSlider_J4.setMaximum(j4_max)
        self.horizontalSlider_J5.setMinimum(j5_min)
        self.horizontalSlider_J5.setMaximum(j5_max)
        self.horizontalSlider_J6.setMinimum(j6_min)
        self.horizontalSlider_J6.setMaximum(j6_max)
        self.label_j1_min.setText(j1_min.__str__())
        self.label_j1_max.setText(j1_max.__str__())
        self.label_j2_min.setText(j2_min.__str__())
        self.label_j2_max.setText(j2_max.__str__())
        self.label_j3_min.setText(j3_min.__str__())
        self.label_j3_max.setText(j3_max.__str__())
        self.label_j4_min.setText(j4_min.__str__())
        self.label_j4_max.setText(j4_max.__str__())
        self.label_j5_min.setText(j5_min.__str__())
        self.label_j5_max.setText(j5_max.__str__())
        self.label_j6_min.setText(j6_min.__str__())
        self.label_j6_max.setText(str(j6_max))

    def start_Runing(self):
        self.main_threading = Thread(target=run)
        self.main_threading.start()

    def send_startFeed_button_click(self):
        num = self.horizontalSlider_feedingNum.value()
        line_index = str(self.comboBox_lineIndex.currentIndex()+1)
        self.command_quene.put(FeedCommand(FeedingConfig(num, line_index)))
        self.stackedWidget_num.setCurrentIndex(1)

    def send_num_button_click(self):
        button = self.sender()
        if button.text() != "自定义":
            num = int(button.text())
            self.horizontalSlider_feedingNum.setMaximum(num)
            self.horizontalSlider_feedingNum.setValue(0)
        else:
            self.pushButton_num_free.hide()



    def send_addNum_button_click(self):
        self.feeding.feedConfig.num +=1

    def send_subNum_button_click(self):
        self.feeding.feedConfig.num -=1

    def send_custom_num_returnPressed(self):
        self.pushButton_num_free.show()
        self.lineEdit_num.hide()
        self.horizontalSlider_feedingNum.setValue(int(self.lineEdit_num.text()))

    def slider_valueChanged(self):
        global last_time
        now_time = time.time()
        if(now_time-last_time) < 2:
            return
        last_time = now_time
        position_instruction = Instruction()
        position_instruction.m0 = self.horizontalSlider_J1.value()
        position_instruction.m1 = self.horizontalSlider_J2.value()
        position_instruction.m2 = self.horizontalSlider_J3.value()
        position_instruction.m3 = self.horizontalSlider_J4.value()
        position_instruction.m4 = self.horizontalSlider_J5.value()
        position_instruction.m5 = self.horizontalSlider_J6.value()

        self.textEdit_j1.setText(str(self.horizontalSlider_J1.value()))
        self.textEdit_j2.setText(str(self.horizontalSlider_J2.value()))
        self.textEdit_j3.setText(str(self.horizontalSlider_J3.value()))
        self.textEdit_j4.setText(str(self.horizontalSlider_J4.value()))
        self.textEdit_j5.setText(str(self.horizontalSlider_J5.value()))
        self.textEdit_j6.setText(str(self.horizontalSlider_J6.value()))

        instruction_command = CMDInstructRequest()
        instruction_command.instructions.append(vars(position_instruction))
        request_command = vars(instruction_command)
        print(request_command)
        self.robotClient.add_sendQuene(request_command)

    def on_button_click(self):
        self.button.setText("Clicked!")

    def send_position_button_click(self):
        # if True:
        #     cmd_command = CMDRequest()
        #     cmd_command.cmdData = ['rewriteData', '800', f'{position_instruction.m0}', 0]
        #     request_command = vars(cmd_command)
        #     self.robotClient.add_sendQuene(request_command)
        return





    


    def run(self):
        while True:

            if not self.command_quene.empty():
                command = self.command_quene.get()
                if isinstance(command, FeedCommand) and command.status == Status.Prepareing:
                    if self.feeding.feedStatus == FeedStatus.FNone:
                        self.feeding.feedConfig = command.feed_config
                        self.feeding.feedStatus = FeedStatus.FStart
                        command.status = Status.Runing


            self.feeding.run()
            updateUI(self)

        #pass #主线程

    def updateUI(self):
        if self.robotClient.is_Connect():
            self.set_label_status_style(True)
        else:
            self.set_label_status_style(False)
        self.horizontalSlider_feedingNum.setValue(self.horizontalSlider_feedingNum.maximum()-self.feeding.feedConfig.num)
        if self.horizontalSlider_feedingNum.value() == 0:
            self.stackedWidget_num.setCurrentIndex(0)
        else:
            self.stackedWidget_num.setCurrentIndex(1)

        self.label_date.setText(datetime.now().strftime("%Y-%m-%d"))
        self.label_time.setText(datetime.now().strftime("%H:%M:%S"))

    def set_label_status_style(self,connected:bool):
        palette = self.label_connect_status.palette()
        if connected:
            self.label_connect_status.setStyleSheet("""
               QLabel {
                        background-color: #A2EF4D;  /* 设置背景颜色 */
                        color: #ffffff;  /* 设置字体颜色 */
                        border-radius: 8px;  /* 圆角半径设置为 QLabel 的一半，形成圆形 */
                        border: 1px solid #A2EF4D;  /* 设置边框颜色和宽度 */
                        qproperty-alignment: 'AlignCenter';  /* 设置文本居中 */
                     }

               """)
        else:
            self.label_connect_status.setStyleSheet("""
                            QLabel {
                        background-color: #FD3251;  /* 设置背景颜色 */
                        color: #ffffff;  /* 设置字体颜色 */
                        border-radius: 8px;  /* 圆角半径设置为 QLabel 的一半，形成圆形 */
                        border: 1px solid #FD3251;  /* 设置边框颜色和宽度 */
                        qproperty-alignment: 'AlignCenter';  /* 设置文本居中 */
                            }
                        """)

    def send_position_command(self, position):
        self.robotClient.add_sendQuene(position)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
